# utils/categories.py

from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():
    """获取商品分类"""
    # 准备商品分类对应的字典，创建有序字典
    categories = OrderedDict()
    # 获取所有的商品频道
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 遍历商品频道
    for channel in channels:
        # 获取频道组
        group_id = channel.group_id
        # 构造基本的字典
        if group_id not in categories:
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }
        # 获取频道组对应的商品分类
        cate1 = channel.category
        # cate1 添加到频道 channels,将频道组对应的商品分类添加到频道组
        categories[group_id]['channels'].append({
            'id': cate1.id,
            'name': cate1.name,
            'url': channel.url
        })
        # 查询二级和三级类别
        for cat2 in cate1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            # 将二级类别添加到一级类别的 sub_cats
            categories[group_id]['sub_cats'].append(cat2)
    return categories